package com.view.mediator
{
	import com.ApplicationFacade;
	import com.model.proxy.ComponentStateProxy;
	import com.view.component.MainView;

	import flash.events.Event;

	import org.puremvc.as3.multicore.utilities.statemachine.StateMachine;
	import org.puremvc.as3.multicore.interfaces.IMediator;
	import org.puremvc.as3.multicore.interfaces.INotification;
	import org.puremvc.as3.multicore.patterns.mediator.Mediator;

	public class MainViewMediator extends Mediator implements IMediator
	{
		public static const NAME:String='MainViewMediator';
		public static const STATES_SWITCHER:String='StatesSwitcher';

		public function MainViewMediator(viewComponent:Object)
		{
			super(NAME, viewComponent);
		}

		protected function get mainView():MainView
		{
			return viewComponent as MainView;
		}

		override public function onRegister():void
		{
			facade.registerProxy(new ComponentStateProxy());
			mainView.addEventListener(MainView.MAIN_STACK, onViewCreated);
		}

		override public function listNotificationInterests():Array
		{
			return [MainViewMediator.STATES_SWITCHER];
		}

		override public function handleNotification(note:INotification):void
		{
			switch (note.getName())
			{
				case MainViewMediator.STATES_SWITCHER:
					mainView.changeSelectedView(note.getBody() as String);
					break;
			}
		}

		protected function onViewCreated(event:Event):void
		{
			checkForMediator(mainView.activeView);
		}

		protected function checkForMediator(child:Object):void
		{
			mainView.visitedViews++;
			switch (child.id)
			{
				case "OneView":
					if (!facade.hasMediator(OneViewMediator.NAME))
						facade.registerMediator(new OneViewMediator(child));
					break;
				case "TwoView":
					if (!facade.hasMediator(TwoViewMediator.NAME))
						facade.registerMediator(new TwoViewMediator(child));
					break;
				case "ThreeView":
					if (!facade.hasMediator(ThreeViewMediator.NAME))
						facade.registerMediator(new ThreeViewMediator(child));
					break;
				case "FourView":
					if (!facade.hasMediator(FourViewMediator.NAME))
						facade.registerMediator(new FourViewMediator(child));
					break;
			}
			if (mainView.visitedViews == mainView.numberOfViews)
			{
				mainView.removeEventListener(MainView.MAIN_STACK, onViewCreated);
				mainView.removeMyListeners();
			}
		}
	}
}